package com.ponhu.ea2.stockcenter.provider.utils;

import com.alibaba.fastjson.JSON;
import com.ponhu.ea2.stockcenter.enums.FileTypeEnum;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.processing.OperationStatus;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @Description: 七牛 文件上传工具类
 * @Author: LiuKai
 * @Created: 2021/4/30
 */
public class QiNiuUploadUtils {

    private final static Logger logger = LogManager.getLogger(QiNiuUploadUtils.class);


    public static final List<String> IMAGE_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png");

    public static final String IMAGE = "image";

    public static final String FILE = "file";

    public static final String accessKey = "yrSnX2zcYGcjiPUcRiIKOePkeZAOxBGi5jHToScd";
    private static final String secretKey = "OaeDmAZBwUHhD1YTQ8akK1NgfuQvH4wDgBa3f_Cj";
    private static final String bucketName = "phping";
    private static final String cdnUrlBase = "https://img-ppcdn.ponhu.cn/";

    /**
     * @Description: 七牛图片上传（七牛只支持单个文件上传）
     * @Param file: 图片文件
     * @Param useChannel:  Test - 测试  OnlineBanking  OnlineAppraisal - 线上图片鉴定  （相当于文件夹名称）
     * @return: java.lang.String 图片地址
     * @Author: LiuKai
     * @Created: 2021/4/30
     */
    public static String uploadPicture(@RequestParam(value = "file") MultipartFile file) throws IOException {
        if (file == null) {
            return null;
        }
        // 默认不指定key的情况下，以文件内容的hash值作为文件名
        String fileName = file.getOriginalFilename();
        // 文件后缀
        String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String newFileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000);

        // 新的文件名
        fileName = newFileName + fileF;
        String cjFileName150 = fileName + "-s150";
        String cjFileName350 = fileName + "-ms350";

        // 数据处理指令，支持多个指令
        String saveJpgEntry = String.format("%s:%s", bucketName, cjFileName150);
        String vframeJpgFop = String.format("%s|saveas/%s", "imageView2/5/w/150/h/150", UrlSafeBase64.encodeToString(saveJpgEntry));
        String save350JpgEntry = String.format("%s:%s", bucketName, cjFileName350);
        String vframeJpgFop350 = String.format("%s|saveas/%s", "imageView2/5/w/350/h/350", UrlSafeBase64.encodeToString(save350JpgEntry));

        // 将多个数据处理指令拼接起来
        String persistentOpfs = StringUtils.join(new String[]{
                vframeJpgFop, vframeJpgFop350
        }, ";");

        // 数据处理队列名称，必填
        StringMap putPolicy = new StringMap();
        putPolicy.put("persistentOps", persistentOpfs);
        putPolicy.put("persistentPipeline", "mps-pipe1");
        putPolicy.put("persistentNotifyUrl", "");// 数据处理完成结果通知地址
        //long expireSeconds = 3600;
        //String upToken = auth.uploadToken(bucketName, null, expireSeconds, putPolicy);

        // 构造一个带指定Zone对象的配置类 //华东Zone.zone0()华北Zone.zone1()华南Zone.zone2()
        Configuration cfg = new Configuration(Zone.zone0());

        //  ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);

        // 构建持久化数据处理对象
        OperationManager operationManager = new OperationManager(auth, cfg);
        try {
            byte[] uploadBytes = file.getBytes();
            String upToken = auth.uploadToken(bucketName);
            Response response = uploadManager.put(uploadBytes, fileName, upToken);

            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(),DefaultPutRet.class);
            String persistentId = operationManager.pfop(bucketName, fileName, persistentOpfs, putPolicy);

            //可以根据该 persistentId 查询任务处理进度
            logger.info("persistentId" + persistentId);
            OperationStatus operationStatus = operationManager.prefop(persistentId);

            //解析 operationStatus 的结果
            logger.info("operationStatus" + operationStatus);
            return cdnUrlBase + fileName;
        } catch (Exception ex) {
            //ignore
            logger.error(ExceptionUtils.getMessage(ex));
            return null;
        }
    }

    /**
     * 普通上传
     *
     * @param file 文件
     * @param fileType 上传类型 {@link FileTypeEnum}
     * @return
     */
    public static String uploadFile(File file, FileTypeEnum fileType) {
        // zone0华东区域,zone1是华北区域,zone2是华南区域
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成上传凭证，然后准备上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = null;
        String path = null;
        // 可以在此处增加不同类型文件的判断处理
        if (FileTypeEnum.IMAGE.equals(fileType)) {
            upToken = auth.uploadToken(bucketName);
            path = cdnUrlBase;
        } else if (FileTypeEnum.FILE.equals(fileType)) {
            upToken = auth.uploadToken(bucketName);
            path = cdnUrlBase;
        }
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            Response response = uploadManager.put(fileInputStream, null, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(),DefaultPutRet.class);
            return path + putRet.key;
        } catch (Exception e) {
            logger.error("上传七牛云错误：{}", e);
            e.printStackTrace();
            // 请求失败时打印的异常的信息
            return "";
        }
    }

    /**
     * 七牛云上传Excel文件
     * @param bos
     * @param fileName
     * @return 路径
     */
    public static String uploadExcelFile(ByteArrayOutputStream bos,String fileName) {
        // zone0华东区域,zone1是华北区域,zone2是华南区域
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        // 生成上传凭证，然后准备上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = null;
        String path = null;
        // 可以在此处增加不同类型文件的判断处理
        upToken = auth.uploadToken(bucketName);
        path = cdnUrlBase;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bos.toByteArray());
            Response response = uploadManager.put(byteArrayInputStream, fileName, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(),DefaultPutRet.class);
            return path + putRet.key;
        } catch (Exception e) {
            logger.error("上传七牛云错误：{}", e);
            e.printStackTrace();
            // 请求失败时打印的异常的信息
            return "";
        }
    }

    /**
     * MultipartFile 转 File
     * @param multiFile
     * @return
     */
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}